﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Collections;
using System.Reflection;
using CoMiCommon;

namespace CoolChat
{
    public class Tools
    {
        public static object GetValueFromRow(DataRow row, string cName)
        {
            try
            {
                return row[cName];
            }
            catch
            {
                return null;
            }
        }

        /// <summary>
        /// MD5加密
        /// </summary>
        /// <param name="str">要加密的字串</param>
        /// <param name="code">16代表16位加密,其它数字代表32位</param>
        /// <returns>返回加密好的小写字串</returns>
        public static string md5(string str, int code)
        {
            if (code == 16) //16位MD5加密（取32位加密的9~25字符） 
            {
                return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5").ToLower().Substring(8, 16);
            }
            else//32位加密 
            {
                return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str + "*($dsfjhk#$Y", "MD5").ToLower();
            }
        }
        /// <summary>
        /// 所有的身份验证都在于此,数据库的用户表将只存入符合在线规则的用户,不在线的用户将从数据库删除
        /// </summary>
        /// <returns></returns>
        public static ChatUser getCurUser()
        {

            if (HttpContext.Current == null)
                return null;
            return (ChatUser)HttpContext.Current.Session["chatuser"];
        }
        public static void setCurUser(ChatUser u)
        {
            if (HttpContext.Current != null)
            {
                HttpContext.Current.Session["chatuser"] = u;
                HttpCookie co = new HttpCookie("ASP.NET_SessionId", HttpContext.Current.Session.SessionID);
                //co.Expires = DateTime.Now.AddMinutes(HttpContext.Current.Session.Timeout);
                co.Path = "/";
                HttpContext.Current.Response.Cookies.Add(co);
            }
        }

        public static void setCookieUser(ChatUser u)
        {
            if (HttpContext.Current != null)
            {
                HttpCookie co = new HttpCookie("chatuser", LitJson.JsonMapper.ToJson(u));
                co.Path = "/";
                HttpContext.Current.Response.Cookies.Add(co);
            }
        }
        public static ChatUser getCookieUser()
        {
            try
            {
                if (HttpContext.Current != null)
                {
                    string cook = HttpContext.Current.Request.Form["c"];
                    Log.error("get forms user: ", cook);
                    try
                    {
                        if (string.IsNullOrEmpty(LitJson.JsonMapper.ToObject<ChatUser>(cook).UserName.Trim()))
                        {
                            cook = null;
                        }
                    }
                    catch
                    {
                        cook = null;
                    }
                    if (string.IsNullOrEmpty(cook))
                    {
                        cook = HttpContext.Current.Request.Cookies["chatuser"].Value;
                        Log.error("get cookie now: ", cook);                       
                    }
                    return LitJson.JsonMapper.ToObject<ChatUser>(cook);
                }
                Log.error("get cookie null", "");
                return null;
            }
            catch (Exception ex)
            {
                Log.error("get cookie null", "");
                return null;
            }
        }
        public static void DateTimeExForJson(DateTime obj, LitJson.JsonWriter writer)
        {
            writer.Write(obj.ToString("yyyy-MM-dd HH:mm:ss.fff"));
        }

        public static void ExportMsgs(DataSet ds)
        {
            Dictionary<string, string> ci = new Dictionary<string, string>();
            Lang lan = new Lang();
            ci.Add("ID", lan["ZH_CN"]["CHAT_MESSAGE"]["Id"].ToString());
            ci.Add("FromUserName", lan["ZH_CN"]["CHAT_MESSAGE"]["From"].ToString());
            ci.Add("ToUserName", lan["ZH_CN"]["CHAT_MESSAGE"]["To"].ToString());
            ci.Add("KeyWord", lan["ZH_CN"]["CHAT_MESSAGE"]["Keyword"].ToString());
            ci.Add("MsgType", lan["ZH_CN"]["CHAT_MESSAGE"]["Type"].ToString());
            ci.Add("Content", lan["ZH_CN"]["CHAT_MESSAGE"]["Content"].ToString());
            ci.Add("AddTime", lan["ZH_CN"]["CHAT_MESSAGE"]["Addtime"].ToString());
            ci.Add("MsgID", lan["ZH_CN"]["CHAT_MESSAGE"]["MsgID"].ToString());
            ci.Add("MsgTime", lan["ZH_CN"]["CHAT_MESSAGE"]["MsgTime"].ToString());
            foreach (DataColumn dc in ds.Tables[0].Columns)
            {
                if (ci.ContainsKey(dc.ColumnName))
                {
                    dc.ColumnName = ci[dc.ColumnName];
                }
            }
            ExcelExporter excl = new ExcelExporter(HttpContext.Current);
            excl.Export(ds, "Messages.xls");
        }        
    }

    /// <summary>
    /// 定义客户端如何操作
    /// </summary>
    public enum ClientAct
    {
        /// <summary>
        /// 发生了一个错误
        /// </summary>
        ERROR = 0, //错误
        /// <summary>
        /// 消息成功
        /// </summary>
        MSG_SUCCESS = 1, //消息成功
        /// <summary>
        /// 消息错误
        /// </summary>
        MSG_FAILED = 2, //消息错误
        /// <summary>
        /// 重设用户数据,删除当前用户数据,赋予新的数据
        /// </summary>
        RESET_USER = 3, //重设用户数据,删除当前用户数据,赋予新的数据
        /// <summary>
        /// 更新用户数据,未更新的数据将保留
        /// </summary>
        UPDATE_USER = 4, //更新用户数据,未更新的数据将保留
        /// <summary>
        /// 返回了若干消息
        /// </summary>
        REVED_MSGS = 5,
        /// <summary>
        /// 接收消息错误
        /// </summary>
        REVED_ERROE = 6,
        /// <summary>
        /// 用户被下线
        /// </summary>
        LOGOFF = 7,
        /// <summary>
        /// 返回了一个用户集合
        /// </summary>
        USER_LIST = 8
    }

    public enum UserListAct
    {
        NONE= -1,
        FIXED= 0, //FIXED 填充用户列表,如果指示了startFixedOnlineUserList; 
        OFFLINE= 1 //OFFLINE 缓存在服务器中已下线的用户列表
    }

    public class UserListData
    {
        private UserListAct act = UserListAct.NONE;

        public UserListAct Act
        {
            get { return act; }
            set { act = value; }
        }
        private ChatUser[] data;

        public ChatUser[] Data
        {
            get { return data; }
            set { data = value; }
        }

    }
    
    public enum USER_ROLE
    {
        GUEST = 0, //游客
        USER = 1, //用户
        SYSUSER = 2, //系统用户
        SA = 3//超级管理员
    }
    public enum USER_OPTION
    {
        /// <summary>
        /// 无
        /// </summary>
        NONE = -1,
        /// <summary>
        /// 获取在在线用户
        /// </summary>
        GET_ONLINE_USER = 0,
        /// <summary>
        /// 获取系统用户的类型
        /// </summary>
        GET_SYS_USER_TYPE = 1 ,
        /// <summary>
        /// 获取不在线用户
        /// </summary>
        GET_OFFLINE_USER = 2,
        /// <summary>
        /// 获取在线用户和系统用户(不管系统用户是否在线)
        /// </summary>
        GET_ONLINE_USER_AND_SYSUSER=3,
        /// <summary>
        /// 禁言用户
        /// </summary>
        SILENCE_USER = 4,
        /// <summary>
        /// 取消禁言用户
        /// </summary>
        UNSILENCE_USER= 5
    }
    public class SysUserType
    {
        public static string GetTypeName(int typeid)
        {
            return Dbo.GetTypeName(typeid);
        }
        public static string GetSysUserTypeNameJson(string lancode)
        {
            return Dbo.GetSysUserTypeNameJson(lancode);
        }
    }
    public enum MsgType
    {
        SYSMSG = 0, //系统消息
        USERMSG = 1, //用户消息
        SYSUSERMSG = 2, //系统用户消息
        SAMSG = 3, //超级管理员消息
        GUESTMSG = 4, //游客消息
        KEYWORD = 5//关键字消息,无接收者
    }
    public static class KEYWORD
    {
        public static class ZH_CN
        {
            public static readonly string PLAN = "行情策略";
            public static readonly string NONE = "";
        }
        public static class EN_US
        {
            public static readonly string PLAN = "Market strategy";
            public static readonly string NONE = "";
        }
    }
}